package com.sun.huazhi.aitaskservice.common.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * 如果 Python 服务无响应或过慢，WebClient 会在规定时间自动超时。
 * 结合 Resilience4j 的熔断策略，可确保系统稳定性。
 */
@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient() {
        // 配置 Reactor Netty 客户端
        HttpClient httpClient = HttpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) // 连接超时
                .responseTimeout(Duration.ofSeconds(10))            // 响应超时（整个请求）
                .doOnConnected(conn -> conn
                        .addHandlerLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS))   // 读取超时
                        .addHandlerLast(new WriteTimeoutHandler(10, TimeUnit.SECONDS))  // 写入超时
                );

        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }
}
